package com.maxatime.service.impl;

import com.maxatime.dao.ShoppingCartMapper;
import com.maxatime.exception.PhoenixException;
import com.maxatime.pojo.ShoppingCart;
import com.maxatime.pojo.ShoppingCartDTO;
import com.maxatime.service.ShoppingCartService;
import com.maxatime.utils.TimeManagerUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Mr.Zhao
 * @title:
 * @projectName phoenix
 * @description: TODO
 * @date 2021/9/15 21:19
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    Logger log = LogManager.getLogger();


    @Override
    public void
    insertShoppingCart(ShoppingCartDTO record) throws PhoenixException {
        log.info("insertShoppingCart.ShoppingCartDTO::: " + record);
        // 1. 根据入参查询购物车里是否有数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setStudentBasicInfoStudentId(record.getStudentBasicInfoStudentId());
        shoppingCart.setGoodsId(record.getGoodsId());
        shoppingCart.setDeleteFlag("0");
        log.info("shoppingCartMapper.listByAll::: " + shoppingCart);
        List<ShoppingCart> listShoppingCart = shoppingCartMapper.listByAll(shoppingCart);
        log.info("shoppingCartMapper.listByAll-resp::: " + listShoppingCart);

        // ShoppingCart对象赋值
        BeanUtils.copyProperties(record, shoppingCart);
        shoppingCart.setDeleteFlag("0");
        shoppingCart.setUpdateTime(TimeManagerUtil.getCurrentDate());

        if (listShoppingCart.size() > 0) {
            // 2. 如果有数据， update 商品数量
            int count = listShoppingCart.get(0).getCount();
            shoppingCart.setCount(count + 1);
            shoppingCart.setPkId(listShoppingCart.get(0).getPkId());
            log.info("shoppingCartMapper.updateByPrimaryKeySelective Exception::: " + shoppingCart);
            try {
                shoppingCartMapper.updateByPrimaryKeySelective(shoppingCart);
            } catch(Exception e) {
                log.error("shoppingCartMapper.updateByPrimaryKeySelective Exception::: " + shoppingCart);
                throw new PhoenixException("9900", e.getMessage());
            }
        } else {
            // 3. 如果没有数据，insert
            shoppingCart.setCount(1);
            shoppingCart.setCreateTime(TimeManagerUtil.getCurrentDate());
            log.info("shoppingCartMapper.insertSelective::: " + shoppingCart);
            try {
                shoppingCartMapper.insertSelective(shoppingCart);
            } catch(Exception e) {
                log.error("shoppingCartMapper.insertSelective::: " + shoppingCart);
                throw new PhoenixException("9900", e.getMessage());
            }
        }
    }
}
